/*   ro-questions, a plugin for the Rolgps, part of the RolGPS Proyect
 *   Copyright (C) 2009 Pablo Alejandro Costesich <rhfixer@gmail.com>
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 */

package roquestions;

import dataTypes.Article;
import dataTypes.Language;
import dataTypes.SearchEngine;
import java.awt.Color;
import java.awt.Toolkit;
import java.io.File;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.text.BadLocationException;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;

/**
 *
 * @author  xeph
 */
public class RoQuestions extends javax.swing.JInternalFrame {
    
    private String dir = "";
    private boolean standalone = false;
    private File databaseFile = new File(this.dir+File.separator+"wiki.db");
    private Language[] listaIdiomas = new Language[0];
    private Article[] listaArticulos = new Article[0];
    private Vector indexTags = new Vector();
    
    /** Creates new form RoQuestions */
    public RoQuestions(String dir) {
        this.dir = dir;
        initComponents();
        verificarBaseDeDatos();
        getListaDeIdiomas();
        Language lang = new Language();
        lang.setId("1");
        getTodosLosArticulosPorIdioma(lang);
    }
    
    private void verificarBaseDeDatos(){
        databaseFile = new File(this.dir+File.separator+"wiki.db");
        if(!databaseFile.exists()){
            SearchEngine database = new SearchEngine(databaseFile);
            database.deploy();
        }else{
            if(!databaseFile.canRead()){
                dispose();
                Toolkit.getDefaultToolkit().beep(); //Beeps.
            }
        }
    }
    
    private void getListaDeIdiomas(){
        SearchEngine database = new SearchEngine(databaseFile);
        listaIdiomas = database.getAllLanguages();
        for(Language lang : listaIdiomas){
            jComboIdiomas.addItem(lang.getName());
        }
    }
    
    private void getTodosLosArticulosPorIdioma(Language lang){
        Article model = new Article();
        model.setLanguage(lang);
        SearchEngine database = new SearchEngine(databaseFile);
        listaArticulos = database.searchArticle(model);
        actualizarIndex();
    }
    
    private void actualizarIndex(){
        indexTags.clear();
        for(Article art : listaArticulos){
            indexTags.add(art.getTitle());
        }
        jListTemas.setListData(indexTags);
    }
    
    private void darFormatoYMostrar(Article modelo){
        jTextArticle.setText("");
        StyledDocument doc = jTextArticle.getStyledDocument();
        Style baseStyle = doc.addStyle("base", null);
        StyleConstants.setFontFamily(baseStyle, "Lucida Sans Unicode");
        StyleConstants.setFontSize(baseStyle, 14);
        StyleConstants.setFirstLineIndent(baseStyle, 20f);
        StyleConstants.setLeftIndent(baseStyle, 10f);

        Style style = doc.addStyle("bold", baseStyle);
        StyleConstants.setBold(style, true);

        style = doc.addStyle("italic", baseStyle);
        StyleConstants.setItalic(style, true);

        style = doc.addStyle("blue", baseStyle);
        StyleConstants.setForeground(style, Color.blue);

        style = doc.addStyle("underline", baseStyle);
        StyleConstants.setUnderline(style, true);

        style = doc.addStyle("green", baseStyle);
        StyleConstants.setForeground(style, Color.green.darker());
        StyleConstants.setUnderline(style, true);

        style = doc.addStyle("highlight", baseStyle);
        StyleConstants.setForeground(style, Color.yellow);
        StyleConstants.setBackground(style, Color.black);

        style = doc.addStyle("title", baseStyle);
        StyleConstants.setItalic(style, true);
        StyleConstants.setBold(style, true);
        StyleConstants.setFontSize(style, 26);


        try {
            
            doc.insertString(doc.getLength(), modelo.getTitle()+"\n", doc.getStyle("title"));
            doc.insertString(doc.getLength(), "\n"+modelo.getBody(), doc.getStyle("base"));
            jTextArticle.setDocument(doc);
        } catch (BadLocationException ex) {
            Logger.getLogger(RoQuestions.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    

    public void setStandalone(boolean standalone) {
        this.standalone = standalone;
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jSplitPane1 = new javax.swing.JSplitPane();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextArticle = new javax.swing.JTextPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        jListTemas = new javax.swing.JList();
        jLabel1 = new javax.swing.JLabel();
        jTextBusqueda = new javax.swing.JTextField();
        jButtonIndex = new javax.swing.JButton();
        jButtonBuscar = new javax.swing.JButton();
        jComboIdiomas = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jSplitPane1.setDividerLocation(150);

        jTextArticle.setEditable(false);
        jScrollPane2.setViewportView(jTextArticle);

        jSplitPane1.setRightComponent(jScrollPane2);

        jListTemas.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jListTemasMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jListTemas);

        jSplitPane1.setLeftComponent(jScrollPane1);

        jLabel1.setFont(new java.awt.Font("Dialog", 1, 12));
        jLabel1.setText("Buscar:");

        jButtonIndex.setText("Volver al índice");
        jButtonIndex.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonIndexActionPerformed(evt);
            }
        });

        jButtonBuscar.setText("Buscar");
        jButtonBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonBuscarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 680, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextBusqueda, javax.swing.GroupLayout.PREFERRED_SIZE, 305, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jComboIdiomas, 0, 111, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonBuscar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonIndex)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextBusqueda, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonIndex)
                    .addComponent(jButtonBuscar)
                    .addComponent(jComboIdiomas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 333, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonIndexActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonIndexActionPerformed
        // TODO add your handling code here:
        getTodosLosArticulosPorIdioma(listaIdiomas[jComboIdiomas.getSelectedIndex()]);
}//GEN-LAST:event_jButtonIndexActionPerformed

    private void jButtonBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonBuscarActionPerformed
        // TODO add your handling code here:
        SearchEngine database = new SearchEngine(databaseFile);
        listaArticulos = database.searchArticleInTitleOrBody(jTextBusqueda.getText(), listaIdiomas[jComboIdiomas.getSelectedIndex()]);
        actualizarIndex();
        
}//GEN-LAST:event_jButtonBuscarActionPerformed

    private void jListTemasMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListTemasMouseClicked
        // TODO add your handling code here:
        int index = jListTemas.getSelectedIndex();
        darFormatoYMostrar(listaArticulos[index]);
    }//GEN-LAST:event_jListTemasMouseClicked



    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonBuscar;
    private javax.swing.JButton jButtonIndex;
    private javax.swing.JComboBox jComboIdiomas;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JList jListTemas;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JTextPane jTextArticle;
    private javax.swing.JTextField jTextBusqueda;
    // End of variables declaration//GEN-END:variables
    
}
